package com.weaver.seconddev.api.tl.agency_agreement_api;

/**
 * E9原始类路径:com.api.tl.agency_agreement_api.AgencyAgreementPOAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.seconddev.api.tl.purchase_api.*;
import com.weaver.seconddev.api.tl.service.SAPCommonService;
import org.apache.commons.lang3.StringUtils;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

import javax.annotation.Resource;

/**
 * 代理协议创建Po接口
 */
@org.springframework.stereotype.Service("tl_agency_agreement_api_AgencyAgreementPOAction")
public class AgencyAgreementPOAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    public static final org.slf4j.Logger logger_e6f4b62c = LoggerFactory.getLogger(AgencyAgreementPOAction.class);


    @Resource(name = "tl_service_SAPCommonService")
    private SAPCommonService sapCommonService;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String requestId = requestInfo.getRequestid();
        /* 获取创建人ID
 TODO 返回值:createdId 类型发生变化 e9类型:int  e10类型:Long*/
        long createdId = requestInfo.getRequestManager().getUserId();
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + "======Start Create Agency Agreement PO======RequestId:" + requestId + ",CreatedId:" + createdId));
        // 获取PO创建人networkId
        String networkId = null;
        //String queryNetworkIdSql = "select field15 from cus_fielddata where id = ? and scopeid = -1";
        String queryNetworkIdSql = "select field15,eteams.employee.id from  eteams.hrmemployeedefined left join   eteams.employee  ON  eteams.hrmemployeedefined.form_data_id = eteams.employee.formdata\n" +
                "where eteams.employee.id= ? ";
        String poolname = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(queryNetworkIdSql, poolname, createdId);
        if (rs.next()) {
            networkId = Util.null2String(rs.getString("field15"));
        }
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",Applicant Network ID:" + networkId + ",Query SQL:" + queryNetworkIdSql));
        String createPoStatus = SUCCESS;
        // 获取流程对应表单名称
        String mainTableName = requestInfo.getRequestManager().getBillTableName();
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",MainTableName:" + mainTableName));
        //String mainTableQuerySql = "select id,lcbh,fgsjc,fjsc,sqxylx,zlkhjc from " + mainTableName + " where requestid = ?";
        String mainTableQuerySql = "SELECT "+mainTableName+".id AS id, "+mainTableName+".lcbh AS lcbh, "+mainTableName+".fgsjc AS fgsjc, "+mainTableName+".fjsc AS fjsc, "+mainTableName+".sqxylx AS sqxylx\n" +
                "\t, "+mainTableName+".zlkhjc AS zlkhjc\n" +
                "FROM (\n" +
                "\tSELECT b.*, a.requestid\n" +
                "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                "\tWHERE a.dataid = b.form_data_id\n" +
                "\t\tAND a.delete_type = 0\n" +
                "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                ") "+mainTableName+"\n" +
                "WHERE "+mainTableName+".requestid = ?\n" +
                "\tAND "+mainTableName+".delete_type = 0\n" +
                "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",MainTableQuerySql:" + mainTableQuerySql));
        String poolname_we = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(mainTableQuerySql, poolname_we, requestId);
        // 主表ID
        String mainId = "";
        // 流程编号
        String processNo = "";
        // 分公司简称
        String branchAbbreviation = "";
        // 附件ID
        String attachmentId = "";
        // 申请协议类型：0-标准代理协议,1-代理协议补充协议,2-转让协议,3-非标准代理协议
        String applyAgreementType = null;
        // 战略客户简称：8-万科（特殊处理）
        String customerAbbreviate = "";
        if (rs.next()) {
            mainId = Util.null2String(rs.getString("id"));
            processNo = Util.null2String(rs.getString("lcbh"));
            branchAbbreviation = Util.null2String(rs.getString("fgsjc"));
            attachmentId = Util.null2String(rs.getString("fjsc"));
            applyAgreementType = Util.null2String(rs.getString("sqxylx"));
            customerAbbreviate = Util.null2String(rs.getString("zlkhjc"));
        }
        // 代理协议补充协议和转让协议不创建PO，直接返回成功
        if (applyAgreementType.equals("1") || applyAgreementType.equals("2")) {
            String applyAgreementTypeMsg = applyAgreementType.equals("1") ? "代理协议补充协议" : "转让协议";
            logger_e6f4b62c.info(String.valueOf("申请协议类型为：" + applyAgreementTypeMsg + ",不创建PO，直接返回成功"));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", SUCCESS, requestInfo.getRequestManager()));
        }
        // 佣金支付方式表
        String payMethodTableName = requestInfo.getDetailTableInfo().getDetailTable(0).getTableDBName();
        // 供应商信息表
        String supplierInfoTableName = requestInfo.getDetailTableInfo().getDetailTable(1).getTableDBName();
        // 采购明细表
        String purchaseDetailTableName = requestInfo.getDetailTableInfo().getDetailTable(2).getTableDBName();
        // 采购结果表
        String purchaseResultTableName = requestInfo.getDetailTableInfo().getDetailTable(3).getTableDBName();
        // 删除最终采购结果表中本流程的所有结果
       // String deleteHistoryDataSql = "delete from " + purchaseResultTableName + " where mainid = ?";
        String deleteHistoryDataSql = "DELETE FROM e10_core_business."+purchaseResultTableName+"\n" +
                "WHERE "+purchaseResultTableName+".form_data_id = ?\n" +
                "\n" +
                "\tAND "+purchaseResultTableName+".delete_type = 0\n" +
                "\tAND "+purchaseResultTableName+".tenant_key = 'tl2k2r96ty'";
        String poolname_ef = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        boolean deleteResult = rs.executeUpdate(deleteHistoryDataSql, poolname_ef, mainId);
        logger_e6f4b62c.info(String.valueOf("deleteResult:" + deleteResult + ",deleteHistoryDataSql:" + deleteHistoryDataSql));
        String errorMessage;
        // 获取代理商个数
        //String agentCountSql = "select id from " + supplierInfoTableName + " where mainid = ?";
        String agentCountSql = "SELECT "+supplierInfoTableName+".id AS id\n" +
                "FROM e10_core_business."+supplierInfoTableName+"\n" +
                "WHERE "+supplierInfoTableName+".form_data_id = ?\n" +
                "\tAND "+supplierInfoTableName+".delete_type = 0\n" +
                "\tAND "+supplierInfoTableName+".tenant_key = 'tl2k2r96ty'";
        String poolname_vt = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(agentCountSql, poolname_vt, mainId);
        long agentCount = rs.getCounts();
        // 根据供应商代码分组创建PO
        //String groupSupplierSql = "select dlsxh,dlsmcwb,dlsbm,dlfbl from " + supplierInfoTableName + " where mainid = ? group by dlsbm";
        String groupSupplierSql = "SELECT "+supplierInfoTableName+".dlsxh AS dlsxh, "+supplierInfoTableName+".dlsmcwb AS dlsmcwb, "+supplierInfoTableName+".dlsbm AS dlsbm, "+supplierInfoTableName+".dlfbl AS dlfbl\n" +
                "FROM e10_core_business."+supplierInfoTableName+"\n" +
                "WHERE "+supplierInfoTableName+".form_data_id = ?\n" +
                "\tAND "+supplierInfoTableName+".delete_type = 0\n" +
                "\tAND "+supplierInfoTableName+".tenant_key = 'tl2k2r96ty'\n" +
                "GROUP BY "+supplierInfoTableName+".dlsbm";
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",groupSupplierSql:" + groupSupplierSql));
        String poolname_n3 = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(groupSupplierSql, poolname_n3, mainId);
        // 遍历供应商，创建PO
        while (rs.next()) {
            RecordSet purchaseDtlRS = I18nContextUtil.getBean(RecordSet.class);
            // 代理商序号
            String agentNo = Util.null2String(rs.getString("dlsxh"));
            // 代理商名称
            String agentName = Util.null2String(rs.getString("dlsmcwb"));
            // 代理商编码
            String agentCode = Util.null2String(rs.getString("dlsbm"));
            // 代理费比例
            String agencyFeeScale = Util.null2String(rs.getString("dlfbl"));
           // String purchaseDtlSql = "select sapth,network,dlsaje,dlsbje from " + purchaseDetailTableName + " where mainid = ? and wlh not like '%VO%'";
            String purchaseDtlSql = "SELECT sapth AS sapth, network AS network, dlsaje AS dlsaje, dlsbje AS dlsbje\n" +
                    "FROM e10_core_business."+purchaseDetailTableName+"\n" +
                    "WHERE "+purchaseDetailTableName+".form_data_id = ?\n" +
                    "\tAND wlh NOT LIKE '%VO%'\n" +
                    "\tAND "+purchaseDetailTableName+".delete_type = 0\n" +
                    "\tAND "+purchaseDetailTableName+".tenant_key = 'tl2k2r96ty'";
            logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",PurchaseDtlSql:" + purchaseDtlSql));
            String poolname_f0 = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            purchaseDtlRS.executeQuery(purchaseDtlSql, poolname_f0, mainId);
            // 序号:初始值为0，每行递增10（例如：10，20,30）
            long detailId = 0L;
            // 数量
            double quantity = 1;
            // 单位
            String unit = "ST";
            // Account Assignment
            String accountAssignment = "P";
            // 采购成本价（含税价）
            double grossPrice = 0;
            // SAP梯号
            String sapElevator = "";
            String network = "";
            // 物料
            String material = "CNR5031-PN";
            // 创建PO唯一标识，用于SAP防止重复创建PO
            String extProcessID = "BPM_" + requestId + "_" + agentCode;
            PoHeader poHeader = new PoHeader();
            PoHeaderText poHeaderText;
            poHeader.setVendor(agentCode);
            if (StringUtils.isNotBlank(networkId)) {
                poHeader.setCreatedBy(networkId);
            }
            poHeader.setPurchaseGroup("C92");
            poHeader.setPurchaseOrg("KCCA");
            poHeader.setExtProcessID(extProcessID);
            List<PoHeaderText> poHeaderTextList = new ArrayList<>();
            List<PoItem> poItemList = new ArrayList<>();
            // 佣金支付方式赋值
            String text1;
            String text2;
            String text3;
            String payMethod1;
            String payMethod2;
            RecordSet payMethodDtlRS = I18nContextUtil.getBean(RecordSet.class);
           // String payMethodDtlSql = "select yjzffs,yjzffs2,wb1,wb2,wb3,sfwzd from " + payMethodTableName + " where mainid = ? order by yjzffs asc";
            String payMethodDtlSql = "SELECT "+payMethodTableName+".yjzffs AS yjzffs, "+payMethodTableName+".yjzffs2 AS yjzffs2, "+payMethodTableName+".wb1 AS wb1, "+payMethodTableName+".wb2 AS wb2, "+payMethodTableName+".wb3 AS wb3\n" +
                    "\t, "+payMethodTableName+".sfwzd AS sfwzd\n" +
                    "FROM e10_core_business."+payMethodTableName+"\n" +
                    "WHERE "+payMethodTableName+".form_data_id = ?\n" +
                    "\tAND "+payMethodTableName+".delete_type = 0\n" +
                    "\tAND "+payMethodTableName+".tenant_key = 'tl2k2r96ty'\n" +
                    "ORDER BY "+payMethodTableName+".yjzffs ASC";
            // 战略客户为万科 and 两个代理商，代理商A传总代佣金支付方式，代理商B传非总代佣金支付方式
            if (customerAbbreviate.equals("8") && agentCount == 2) {
                if (agentNo.equals("1")) {
                    //payMethodDtlSql = "select yjzffs,yjzffs2,wb1,wb2,wb3,sfwzd from " + payMethodTableName + " where mainid = ? and sfwzd = 0 order by yjzffs asc";
                    payMethodDtlSql = "SELECT "+payMethodTableName+".yjzffs AS yjzffs, "+payMethodTableName+".yjzffs2 AS yjzffs2, "+payMethodTableName+".wb1 AS wb1, "+payMethodTableName+".wb2 AS wb2, "+payMethodTableName+".wb3 AS wb3\n" +
                            "\t, "+payMethodTableName+".sfwzd AS sfwzd\n" +
                            "FROM e10_core_business."+payMethodTableName+"\n" +
                            "WHERE "+payMethodTableName+".form_data_id = ?\n" +
                            "\tAND "+payMethodTableName+".delete_type = 0\n" +
                            "\tAND "+payMethodTableName+".sfwzd = 0\n" +
                            "\tAND "+payMethodTableName+".tenant_key = 'tl2k2r96ty'\n" +
                            "ORDER BY "+payMethodTableName+".yjzffs ASC";
                } else if (agentNo.equals("2")) {
                    //payMethodDtlSql = "select yjzffs,yjzffs2,wb1,wb2,wb3,sfwzd from " + payMethodTableName + " where mainid = ? and sfwzd = 1 order by yjzffs asc";
                    payMethodDtlSql = "SELECT "+payMethodTableName+".yjzffs AS yjzffs, "+payMethodTableName+".yjzffs2 AS yjzffs2, "+payMethodTableName+".wb1 AS wb1, "+payMethodTableName+".wb2 AS wb2, "+payMethodTableName+".wb3 AS wb3\n" +
                            "\t, "+payMethodTableName+".sfwzd AS sfwzd\n" +
                            "FROM e10_core_business."+payMethodTableName+"\n" +
                            "WHERE "+payMethodTableName+".form_data_id = ?\n" +
                            "\tAND "+payMethodTableName+".delete_type = 0\n" +
                            "\tAND "+payMethodTableName+".sfwzd = 1\n" +
                            "\tAND "+payMethodTableName+".tenant_key = 'tl2k2r96ty'\n" +
                            "ORDER BY "+payMethodTableName+".yjzffs ASC";
                }
            }
            String poolname_qz = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            payMethodDtlRS.executeQuery(payMethodDtlSql, poolname_qz, mainId);
            while (payMethodDtlRS.next()) {
                poHeaderText = new PoHeaderText();
                text1 = Util.null2String(payMethodDtlRS.getString("wb1"));
                text2 = Util.null2String(payMethodDtlRS.getString("wb2"));
                text3 = Util.null2String(payMethodDtlRS.getString("wb3"));
                payMethod1 = Util.null2String(payMethodDtlRS.getString("yjzffs"));
                payMethod2 = Util.null2String(payMethodDtlRS.getString("yjzffs2"));
                poHeaderText.setTextID("F07");
                poHeaderText.setTextLine(text1 + payMethod1 + text2 + payMethod2 + text3);
                poHeaderTextList.add(poHeaderText);
            }
            // 代理费比例赋值
            poHeaderText = new PoHeaderText();
            poHeaderText.setTextID("F01");
            poHeaderText.setTextLine("合同设备总价(不包括运输费及保险费) " + agencyFeeScale + "% 的佣金");
            poHeaderTextList.add(poHeaderText);
            List<PoAccount> poAccountList = new ArrayList<>();
            logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + "======According To Agent Details Create PO Start======AgentCode:" + agentCode));
            // 遍历供应商明细信息，拼报文
            while (purchaseDtlRS.next()) {
                detailId += 10;
                // 代理商序号和代理商金额对应关系：1-dlsaje，2-dlsbje
                String agentAmount = null;
                if (agentNo.equals("1")) {
                    agentAmount = Util.null2String(purchaseDtlRS.getString("dlsaje"));
                } else if (agentNo.equals("2")) {
                    agentAmount = Util.null2String(purchaseDtlRS.getString("dlsbje"));
                }
                sapElevator = Util.null2String(purchaseDtlRS.getString("sapth"));
                network = Util.null2String(purchaseDtlRS.getString("network"));
                if (StringUtils.isNotBlank(agentAmount)) {
                    try {
                        grossPrice = new DecimalFormat().parse(agentAmount).doubleValue();
                    } catch (ParseException e) {
                        logger_e6f4b62c.error(e.getMessage());
                        throw new RuntimeException(e);
                    }
                }
                // 代理费金额为null或小于等于0，跳过该明细
                if (grossPrice <= 0) {
                    logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",该明细代理费金额为null或小于等于0，跳过该明细，SAP梯号：" + sapElevator));
                    continue;
                }
                PoItem poItem = new PoItem();
                PoAccount poAccount = new PoAccount();
                poItem.setItemNumber(String.valueOf((int) detailId));
                int processNoLength = processNo.length();
                // 截取后7位流程编号
                if (processNoLength >= 7) {
                    String processNoSuffix = processNo.substring(processNoLength - 6);
                    String versionNo = processNo.substring(3, 5);
                    poItem.setRequirementTrackingNr(versionNo + branchAbbreviation + processNoSuffix);
                }
                poItem.setAcctAssCat(accountAssignment);
                poItem.setMaterial(material);
                poItem.setPlant("KCC");
                poItem.setShortText(sapElevator);
                poItem.setQuantity(quantity);
                poItem.setUnit(unit);
                poItem.setPriceUnit(unit);
                poItem.setGrossPrice(grossPrice);
                poAccount.setItemNumber(String.valueOf((int) detailId));
                poAccount.setNetwork(network);
                poAccount.setActivity("2200");
                poItemList.add(poItem);
                poAccountList.add(poAccount);
            }
            // 构造请求报文
            JsonMessageBuild jsonMessageBuild = new JsonMessageBuild();
            PoReqMessage poReqMessage = jsonMessageBuild.buildPoRequestMessage(poHeader, null, poHeaderTextList, poItemList, null, null, poAccountList, null);
            // 调用创建PO接口
            Map<String, String> resultMap = sapCommonService.createPurchaseOrder(requestId, poReqMessage, createPoStatus, agentCode);
            errorMessage = resultMap.get("errorMessage");
            createPoStatus = resultMap.get("createPoStatus");
            String purchaseOrder = resultMap.get("purchaseOrder");
            // 将创建Po和上传附件结果记录到采购结果表中
            RecordSet purchaseResultRS = I18nContextUtil.getBean(RecordSet.class);
            String insertPurchaseResultSql = "insert into " + purchaseResultTableName + "(id,form_data_id,poh,gysmc,gysdm,fhxx,delete_type,tenant_key) values(?,?,?,?,?,?,?,?)";
            String poolname_ju = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean insertResult = purchaseResultRS.executeUpdate(insertPurchaseResultSql, poolname_ju, IdGenerator.generate(),mainId, purchaseOrder, agentName, agentCode, errorMessage,"0","tl2k2r96ty");
            logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",InsertPurchaseResultSql:" + insertPurchaseResultSql + ",Insert " + purchaseResultTableName + " Table Status:" + insertResult));
            // PO创建成功，先把PO号记录到代理商信息表中，然后开始上传附件
            if (StringUtils.isNotBlank(purchaseOrder)) {
                // PO号记录到代理商信息表
                RecordSet agentInfoRS = I18nContextUtil.getBean(RecordSet.class);
               // String updatePOResultSql = "update " + supplierInfoTableName + " set poh = ? where mainid = ? and dlsbm = ?";
                String updatePOResultSql = "UPDATE e10_core_business."+supplierInfoTableName+"\n" +
                        "SET poh = ?\n" +
                        "WHERE "+supplierInfoTableName+".form_data_id = ?\n" +
                        "\tAND dlsbm = ?\n" +
                        "\n" +
                        "\tAND "+supplierInfoTableName+".delete_type = 0\n" +
                        "\tAND "+supplierInfoTableName+".tenant_key = 'tl2k2r96ty'";
                String poolname_xh = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean updatePOResult = agentInfoRS.executeUpdate(updatePOResultSql, poolname_xh, purchaseOrder, mainId, agentCode);
                logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",UpdatePOResultSql:" + updatePOResultSql + ",Update " + supplierInfoTableName + " Table Status:" + updatePOResult));
                // 如果附件ID存在，上传PO附件；不存在上传附件结果直接赋值success
                if (StringUtils.isNotBlank(attachmentId)) {
                    errorMessage = sapCommonService.uploadAttachments(requestId, purchaseOrder, attachmentId);
                    if (!errorMessage.equals("success")) {
                        createPoStatus = FAILURE_AND_CONTINUE;
                    }
                } else {
                    logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",No Attachments Uploaded,Return Success"));
                    errorMessage = "success";
                }
                // 将上传附件的结果更新到采购结果表中
                logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",Record The Uploading Attachments Result In The Purchase Result Table"));
                RecordSet updateUploadResultRS = I18nContextUtil.getBean(RecordSet.class);
                //String updateSql = "update " + purchaseResultTableName + " set fhxx = ? where mainid = ? and gysdm = ? and poh = ?";
                String updateSql = "UPDATE e10_core_business."+purchaseResultTableName+"\n" +
                        "SET fhxx = ?\n" +
                        "WHERE "+purchaseResultTableName+".form_data_id = ?\n" +
                        "\tAND gysdm = ?\n" +
                        "\tAND poh = ?\n" +
                        "\tAND "+purchaseResultTableName+".delete_type = 0\n" +
                        "\tAND "+purchaseResultTableName+".tenant_key = 'tl2k2r96ty'";
                String poolname_qg = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean updateResult = updateUploadResultRS.executeUpdate(updateSql, poolname_qg, errorMessage, mainId, agentCode, purchaseOrder);
                logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",UpdateSql:" + updateSql + ",Update " + purchaseResultTableName + " Table Status:" + updateResult));
            } else {
                logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + ",Create PO Failed, No Longer Uploading Attachments"));
            }
            logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + ",AgentCode:" + agentCode + "======According To Agent Details Create PO Complete======"));
        }
        logger_e6f4b62c.info(String.valueOf("RequestId:" + requestId + "======Complete Create Agency Agreement PO======ReturnResult:" + createPoStatus));
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", createPoStatus, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
